package cn.chenc.framework.core.util;


import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 　@description: TODO
 * 　@author secret
 * 　@date 2021/3/22 11:42
 *
 */
public class ValidatorUtil {

    private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验对象
     *
     * @param object 待校验对象
     * @param groups 待校验的组
     * @return 返回消息list
     */
    public static List<String> validateEntityAll(Object object, Class<?>... groups) {
        List<String> list=new ArrayList<>();
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            constraintViolations.forEach(o -> {
                list.add(o.getMessage());
            });
        }
        return list;
    }

    /**
     * 校验对象
     *
     * @param object 待校验对象
     */
    public static List<String> validateEntityAll(Object object) {
        List<String> list=new ArrayList<>();
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object);
        if (!constraintViolations.isEmpty()) {
            constraintViolations.forEach(o -> {
                list.add(o.getMessage());
            });
        }
        return list;
    }

    /**
     * 校验对象
     *
     * @param object 待校验对象
     * @param groups 待校验的组
     * @return 返回单个校验消息
     */
    public static String validateEntityFirst(Object object, Class<?>... groups) {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            for(ConstraintViolation<Object> o:constraintViolations){
                return o.getMessage();
            }
        }
        return null;
    }

    /**
     * 校验对象
     * @param object 待校验对象
     * @return 返回单个校验消息
     */
    public static String validateEntityFirst(Object object) {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object);
        if (!constraintViolations.isEmpty()) {
            for(ConstraintViolation<Object> o:constraintViolations){
                return o.getMessage();
            }
        }
        return null;
    }


}
